<template>
  <view>
    <!-- 收银台 -->
    <view class="edgeInsetTop"></view>
    <view class="wanl-pay">
      <view class="money bg-white">
        <text class="title">充值金额</text>
        <view class="margin-top price">
          <view class="symbol">
            <text>￥</text>
          </view>
          <input type="digit" maxlength="5" focus v-model="money" />
          <view class="text-lg wanl-gray-light" @tap="emptyInput" v-if="money">
            <text class="wlIcon-shibai"></text>
          </view>
        </view>
      </view>
      <view class="list-box">
        <view class="item" v-for="(item, index) in payList" :key="index">
          <text :class="'wlIcon-' + item.type + '-pay'"></text>
          <view class="action">
            <text class="title wanl-pip">{{ item.name }}</text>
            <view>{{ item.describe }}</view>
          </view>
          <view class="radio text-xxl" v-if="item.state" @tap="onSelect(index)">
            <text v-if="item.select" class="wlIcon-xuanze-danxuan wanl-orange"></text>
            <text v-else class="wlIcon-xuanze wanl-gray-light"></text>
          </view>
          <view class="radio text-xxl" v-else>
            <text class="wlIcon-xuanze-danxuan wanl-gray-light"></text>
          </view>
        </view>
      </view>
      <button class="mix-btn wanl-bg-redorange" @tap="confirm()" :loading="loading">充值</button>
      <view class="footer text-center">
        <!-- <view> © 图奕支付 </view> -->
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      loading: false,
      disabled: false,
      money: null,
      payList: [],
    };
  },
  onLoad() {
    // 支付列表
    let method = 'wap';

    // #ifdef H5
    if (this.$jssdk.isWechat()) {
      method = 'mp';
    }
    // #endif

    // #ifdef APP-PLUS
    method = 'app';
    // #endif
    // // #ifdef MP-BAIDU
    // method = 'mini';
    // // #endif
    // #ifdef MP-WEIXIN
    method = 'miniapp';
    // #endif
    // // #ifdef MP-ALIPAY
    // method = 'mini';
    // // #endif
    // // #ifdef MP-QQ
    // method = 'mini';
    // // #endif

    // #ifdef H5
    if (this.$jssdk.isWechat()) {
      // 基本完成,后端未测试,没有完善回调，1.0.8 版本暂时屏蔽
      this.payList.push({
        name: '微信支付',
        describe: '推荐使用微信支付',
        type: 'wechat',
        method: method,
        state: true,
        select: !this.isbalance,
      });
    } else {
      this.payList.push(
        {
          name: '支付宝',
          describe: '',
          type: 'alipay',
          method: method,
          state: true,
          select: false,
        },
        {
          name: '微信支付',
          describe: '推荐使用微信支付',
          type: 'wechat',
          method: method,
          state: true,
          select: !this.isbalance,
        },
      );
    }
    // #endif
    // #ifndef H5
    uni.getProvider({
      service: 'payment',
      success: e => {
        e.provider.map(value => {
          if (value == 'alipay') {
            this.payList.push({
              name: '支付宝',
              describe: '',
              type: value,
              method: method,
              state: true,
              select: false,
            });
          } else if (value == 'wxpay') {
            this.payList.push({
              name: '微信支付',
              describe: '推荐使用微信支付',
              type: 'wechat',
              method: method,
              state: true,
              select: false,
            });
          } else if (value == 'baidu') {
            this.payList.push({
              name: '百度收银台',
              describe: '',
              type: value,
              method: method,
              state: true,
              select: false,
            });
          } else if (value == 'appleiap') {
            this.payList.push({
              name: 'Apple支付',
              describe: '',
              type: 'apple',
              method: method,
              state: true,
              select: false,
            });
          }
        });
      },
    });
    // #endif
  },
  methods: {
    //确认支付
    confirm() {
      let data = null;
      if (this.disabled) {
        return;
      }
      if (this.money <= 0) {
        this.$wanlshop.msg('请输入充值金额');
        return;
      }
      this.payList.map((value, index, array) => {
        if (value.select) {
          data = value;
        } else {
          return;
        }
      });
      // 判断支付是否存在
      if (!data) {
        this.$wanlshop.msg('请选择支付方式');
        return;
      } else {
        this.loading = true;
        this.disabled = true;
        // 获取小程序code
        // #ifdef MP
        uni.login({
          success: e => {
            this.wanlPay(data, e.code);
          },
          fail: e => {
            uni.showModal({
              content: '无法获取微信code,原因为: ' + e.errMsg,
              showCancel: false,
            });
          },
        });
        // #endif
        // #ifndef MP
        this.wanlPay(data);
        // #endif
      }
    },
    async wanlPay(data, code = null) {
      this.$api.post({
        url: '/wanlshop/pay/recharge',
        data: {
          type: data.type,
          method: data.method,
          code: code,
          money: this.money,
        },
        success: res => {
          // 微信 H5支付
          if (data.type == 'wechat' && data.method == 'wap') {
            // 关闭loading
            this.loading = false;
            uni.showModal({
              title: '微信支付',
              content: '是否已完成支付',
              success: res => {
                if (res.confirm) {
                  this.paySuccess();
                } else if (res.cancel) {
                  console.log('用户点击取消');
                }
              },
            });
            // 异步查询是否支付成功
            window.location.href = res;
          }

          // 微信小程序支付
          if (data.type == 'wechat' && data.method == 'miniapp') {
            uni.requestPayment({
              appId: res.appId,
              nonceStr: res.nonceStr,
              package: res.package,
              paySign: res.paySign,
              signType: res.signType,
              timeStamp: res.timeStamp,
              success: e => {
                this.paySuccess();
              },
              fail: e => {
                uni.showModal({
                  content: '支付失败,原因为: ' + e.errMsg,
                  showCancel: false,
                });
              },
              complete: () => {
                this.loading = false;
                this.disabled = false;
              },
            });
          }
          // 支付宝 H5支付
          if (data.type == 'alipay' && data.method == 'wap') {
            // 关闭loading
            this.loading = false;
            document.write(res);
          }
          // 微信JSSDK支付，返回的是配置
          if (data.type == 'wechat' && data.method == 'mp') {
            WeixinJSBridge.invoke(
              'getBrandWCPayRequest',
              {
                appId: res.appId,
                timeStamp: res.timeStamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
                nonceStr: res.nonceStr, // 支付签名随机串，不长于 32 位
                package: res.package, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=\*\*\*）
                signType: res.signType, // 微信支付V3的传入RSA,微信支付V2的传入格式与V2统一下单的签名格式保持一致
                paySign: res.paySign, // 支付签名
              },
              function (res) {
                console.log(res);
                // alert(JSON.stringify("我是支付返回的信息：\n"+res));
                // alert("我是支付返回的信息：\n"+res.err_msg);
                if (res.err_msg == 'get_brand_wcpay_request:ok') {
                  // 使用以上方式判断前端返回,微信团队郑重提示：
                  //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
                  // 支付成功后的回调函数
                  this.paySuccess();
                  this.disabled = false;
                } else {
                  if (err.errMsg == 'chooseWXPay:ok') {
                    this.$wanlshop.msg('支付成功');
                  } else if (err.errMsg == 'chooseWXPay:cancel') {
                    this.$wanlshop.msg('支付失败，取消支付');
                  } else if (err.errMsg == 'chooseWXPay:fail') {
                    this.$wanlshop.msg('支付失败');
                  }
                  this.disabled = false;
                }
              },
            );

            // this.$jssdk.wxpay({
            // 	data: res,
            // 	success: res => {
            // 		this.paySuccess();
            // 	},
            // 	fail: err => {
            // 		if (err.errMsg == "chooseWXPay:ok") {
            // 			this.$wanlshop.msg('支付成功');
            // 		}else if (err.errMsg == "chooseWXPay:cancel") {
            // 			this.$wanlshop.msg('支付失败，取消支付');
            // 		}else if (err.errMsg == "chooseWXPay:fail") {
            // 			this.$wanlshop.msg('支付失败');
            // 		}
            // 	}
            // })
          }
          // APP支付
          if ((data.type == 'alipay' || data.type == 'wechat') && data.method == 'app') {
            let provider = data.type;
            if (data.type == 'wechat') {
              provider = 'wxpay';
            }
            uni.requestPayment({
              provider: provider,
              orderInfo: res,
              success: e => {
                console.log('success', e);
                this.paySuccess();
              },
              fail: e => {
                uni.showModal({
                  content: '支付失败,原因为: ' + e.errMsg,
                  showCancel: false,
                });
              },
              complete: () => {
                this.loading = false;
                this.disabled = false;
              },
            });
          }
        },
      });
    },
    onSelect(key) {
      this.payList.map((value, index, array) => {
        if (index == key) {
          value.select = !value.select;
        } else {
          value.select = false;
        }
      });
    },
    emptyInput() {
      this.money = null;
    },
    // 支付成功
    paySuccess() {
      this.loading = false;
      this.$store.commit('user/setUserInfo', {
        money: this.$wanlshop.bcadd(this.$store.state.user.money, this.money),
      });
      this.$wanlshop.to('/pages/page/success?type=recharge');
    },
  },
};
</script>

<style>
radio-group {
  display: block;
}
.wanl-pay .money {
  padding: 25rpx 40rpx 25rpx 60rpx;
}

.wanl-pay .money .symbol {
  font-size: 60rpx;
  margin-right: 20rpx;
}

.wanl-pay .money .price {
  display: flex;
  align-items: center;
}
.wanl-pay .money .price input {
  /* #ifdef MP */
  height: 100rpx;
  min-height: 100rpx;
  /* #endif */
  width: 100%;
  font-size: 100rpx;
}
</style>
